from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
import os
import platform
import tempfile


class PersistentChromeDriver:
    def __init__(self, profile_name="default"):
        """
        初始化持久化的Chrome驱动
        :param profile_name: 配置文件名称,用于区分不同的配置
        """
        self.profile_name = profile_name
        self.driver = None
        self._setup_user_data_dir()

    def _setup_user_data_dir(self):
        """设置用户数据目录"""
        # 根据操作系统确定配置目录
        if platform.system() == "Windows":
            base_dir = os.path.join(os.environ["LOCALAPPDATA"], "ChromeProfiles")
        else:
            base_dir = os.path.join(os.path.expanduser("~"), ".config", "ChromeProfiles")

        # 确保目录存在
        self.user_data_dir = os.path.join(base_dir, self.profile_name)
        os.makedirs(self.user_data_dir, exist_ok=True)

    def start_browser(self, headless=False):
        """
        启动浏览器
        :param headless: 是否启用无头模式
        :return: webdriver实例
        """
        chrome_options = Options()

        # 设置用户数据目录
        chrome_options.add_argument(f"--user-data-dir={self.user_data_dir}")

        # 其他常用设置
        chrome_options.add_argument("--no-sandbox")
        chrome_options.add_argument("--disable-dev-shm-usage")
        if headless:
            chrome_options.add_argument("--headless")

        # 禁用自动化标识
        chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
        chrome_options.add_experimental_option("useAutomationExtension", False)

        try:
            self.driver = webdriver.Chrome(options=chrome_options,service=Service(r""))
            return self.driver
        except Exception as e:
            print(f"启动Chrome时发生错误: {str(e)}")
            raise

    def quit(self):
        """关闭浏览器"""
        if self.driver:
            try:
                self.driver.quit()
            except Exception as e:
                print(f"关闭Chrome时发生错误: {str(e)}")
            finally:
                self.driver = None